import 'package:valovault_reminder/common/config/val_assets_name.dart';
import 'package:valovault_reminder/common/config/val_client_url_path.dart';
import 'package:valovault_reminder/common/config/val_define_const_data.dart';
import 'package:valovault_reminder/common/util/val_app_state_tool.dart';
import 'package:valovault_reminder/common/util/val_router_manager.dart';
import 'package:valovault_reminder/common/util/val_shared_preferences_tool.dart';
import 'package:valovault_reminder/http/val_dio_fetch_kit.dart';
import 'package:valovault_reminder/pages/base/val_base_ui_page.dart';
import 'package:valovault_reminder/util/val_toast_kit.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../../common/ui/val_ui_kit_dialog_impl.dart';
import '../../common/util/val_logger_manager.dart';
import '../base/val_app_common_bar.dart';

class ValMyHomeSettingPage extends StatefulWidget {
  const ValMyHomeSettingPage({super.key});

  @override
  State<ValMyHomeSettingPage> createState() => _ValMyHomeSettingPageState();
}

class _ValMyHomeSettingPageState extends ValBaseUIPageState<ValMyHomeSettingPage> {
  bool autoTranslate = true;
  String userId = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isAppBar = true;
    bgColor = const Color(0xFF143A42);
    resizeToAvoidBottomInset = false;

    if (ValAppStateTool().accountInfo != null) {
      setState(() {
        userId = ValAppStateTool().accountInfo!.userId;
      });
      readAutoTranslateStateValue();
    }
  }

  @override
  PreferredSizeWidget? get appBar {
    return ValAppCommonBar(
      backgroundColor: Colors.transparent,
      title: 'Setting',
      titleColor: Colors.white,
      brightness: Brightness.dark,
      leadingWidget: GestureDetector(
          onTap: () {
            Navigator.of(context).pop();
          },
          child: Image.asset(
            '${ValAssetsName.ASSETS_MINE}val_my_home_back_btn.png',
            width: 30,
            height: 30,
          )
      ),
    );
  }

  ///自动翻译开关
  void readAutoTranslateStateValue() async {
    autoTranslate = await ValLocalStore.getValue("$userId-${ValDefineConstData.valAutoTranslateKey}", false);
    setState(() {});
  }

  ///点击列表
  void onClickedSettingOptions(int index) {
    if (index == 0) {
      ValToastKit.showMessage('Copy Success');
      Clipboard.setData(ClipboardData(text: userId));
    }
    else if (index == 1) { //自动翻译开关
      ValLocalStore.saveValue("$userId-${ValDefineConstData.valAutoTranslateKey}", autoTranslate);
    }
    else if (index == 2) { //退出登录
      postLogoutActionUrl();
    }
    else if (index == 3) { //删除账号
      confirmRemoveAccount();
    }
  }

  void postLogoutActionUrl() {
    ValUIKitDialogImpl.showProgress();
    ValDioFetchKit.getInstance().postJsonWithUrl(ValClientUrlPath.logout, {}, (data, errorCode, message){
      ValUIKitDialogImpl.closeDialog();
      ValAppStateTool().logout();
      ValRouterManager.gotoLogin();
    }, (err){

    });
  }

  void deleteAccountRequest() {
    ValDioFetchKit.getInstance().postJsonWithUrl(ValClientUrlPath.deleteAccount, {}, (data, errorCode, message) {
      clearAccountData();

      ValRouterManager.gotoLogin();
    }, (err){

    });
  }

  void confirmRemoveAccount() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Are you sure?'),
        content: const Text('Are you sure you want to delete your account?'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(false);
            },
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(true);
              deleteAccountRequest();
            },
            child: const Text('Yes'),
          ),
        ],
      ),
    );
  }

  void clearAccountData() async {
    ValAppStateTool().token = "";
  }

  Widget getTextItem({String title = '', Widget? rightWidget, VoidCallback? onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: getBaseContent(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(title, style: const TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.w500),),
              if (rightWidget != null)
                rightWidget,
            ],
          )
      ),
    );
  }

  Widget getBaseContent({Widget? child}) {
    return Container(
      height: 64,
      width: double.infinity,
      alignment: Alignment.centerLeft,
      margin: const EdgeInsets.only(left: 38, right: 38),
      color: Colors.transparent,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(child: child ?? Container()),
          Container(height: 1, color: const Color.fromRGBO(255, 255, 255, 0.25), ),
        ],
      ),
    );
  }

  @override
  Widget buildBody(BuildContext context) {
    return Stack(
      children: [
        Positioned(
            top: 0, left: 0, right: 0, bottom: 0,
            child: Container(
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topRight,
                    end: Alignment.bottomCenter,
                    colors: [
                      Color(0xFF143A42),
                      Color(0xFF090B24),
                    ],
                  ),))
        ),
        Positioned(
          top: 0, left: 0, right: 0, bottom: 0,
          child: Column(
            children: [
              const Padding(padding: EdgeInsets.only(top: 32)),
              getTextItem(
                title: 'id：$userId',
                rightWidget: Image.asset('${ValAssetsName.ASSETS_MINE}val_my_setting_copy.png', height: 24, width: 24,),
                onTap: () {
                  onClickedSettingOptions(0);
                },
              ),

              getTextItem(
                title: 'Auto Translate',
                rightWidget: Image.asset(ValAssetsName.ASSETS_MINE + (autoTranslate ? 'val_my_setting_open.png' : 'val_my_setting_off.png'), height: 24, width: 24,),
                onTap: () {
                    setState(() {
                      autoTranslate = !autoTranslate;
                      onClickedSettingOptions(1);
                    });
                },
              ),
              getTextItem(
                title: 'Logout',
                // rightWidget: Image.asset('${CsConfig.ASSETS_MINE}mine_setting_arrow.png', height: 16, width: 16,),
                onTap: () {
                  ValLoggerManager.stat(page: ValConfigLoggerPath.logout);
                  onClickedSettingOptions(2);
                },
              ),
              getTextItem(
                title: 'Delete account',
                // rightWidget: Image.asset('${CsConfig.ASSETS_MINE}mine_setting_arrow.png', height: 16, width: 16,),
                onTap: () {
                  onClickedSettingOptions(3);
                  ValLoggerManager.stat(page: ValConfigLoggerPath.deleteaccount);
                },
              ),
            ],
          ),
        ),
      ],
    );
  }
}
